package cn.com.nxt.txb;

import android.content.DialogInterface;
import android.content.Intent;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.netease.nim.uikit.common.ui.dialog.DialogMaker;
import com.netease.nim.uikit.common.util.sys.NetworkUtil;
import com.netease.nimlib.sdk.avchat.AVChatCallback;
import com.netease.nimlib.sdk.avchat.AVChatManager;
import com.netease.nimlib.sdk.avchat.constant.AVChatType;
import com.netease.nimlib.sdk.avchat.model.AVChatChannelInfo;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import cn.com.nxt.txb.avchat.activity.AVChatActivity;
import cn.com.nxt.txb.education.activity.ChatRoomActivity;
import cn.com.nxt.txb.httpdelegate.DialingDelegate;
import cn.com.nxt.txb.httpdelegate.LiveDelegate;
import cn.com.nxt.txb.httpdelegate.MeetingDelegate;
import cn.com.nxt.txb.util.AppUtil;
import cn.com.nxt.txb.widget.ClearEditText;

@ContentView(R.layout.activity_enter_meeting)
public class EnterMeetingActivity extends BaseActivity {
    @ViewInject(R.id.toolbar)
    private Toolbar toolbar;
    @ViewInject(R.id.et_room_id)
    private ClearEditText mRoomIdEt;
    private String phoneOrRoomID;
    private static final int PERMISSION_REQUEST_CODE = 10;
    private MeetingDelegate meetingDelegate;
    private LiveDelegate liveDelegate;
    private DialingDelegate dialingDelegate;
    // private DialingDelegate dialingDelegate;
    private final byte IS_MEETING_BEGIN = 0x20;
    private final byte MEETING_IN_AUTH = 0x21;
    private final byte MEETING_IN_CHECK = 0x22;
    private final byte LIVE_PLAY = 0x23;
    private final byte LIVE_PUBLISH = 0x24;
    private final byte GET_OTHER_NAME = 0x25;
    private final byte GET_OTHER_NAME_MEETING = 0x26;

    //public static String ROOM_NAME = "xiaohehe51";
    //public static boolean isCreate = true;
    public static String name;
    public static String roomid;
    public static String meetingid;
    public static String data;
    public static int status;
    // public static String tempRoomID = "003";

    //{"code":10000,"msg":"success","data":{"name":"测试","roomid":"81893109","status":1}}2345678925","meetingid":"1496
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);//注解绑定
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        meetingDelegate = new MeetingDelegate(this);
        liveDelegate = new LiveDelegate(this);
        dialingDelegate=new DialingDelegate(this);
        // dialingDelegate=new DialingDelegate(this);
    }

    @Event({R.id.tv_enter, R.id.my_meeting})
    private void onViewClick(View v) {
        switch (v.getId()) {
            case R.id.tv_enter:
                enterMeeting();
                break;
            case R.id.my_meeting:
                startMeeting(AppUtil.mUser.getRommid());
                break;
        }
    }

    private void enterMeeting() {
        phoneOrRoomID = mRoomIdEt.getText().toString().trim();
        if (TextUtils.isEmpty(phoneOrRoomID)) {
            showToast("账号/会议号不能为空！");
            return;
        }
        if (!AppUtil.isNumeric(phoneOrRoomID)) {
            showToast("账号/会议号必须为数字！");
            return;
        }
        if ((phoneOrRoomID.length() == 11 && phoneOrRoomID.startsWith("1")) || (phoneOrRoomID.length() == 12 && phoneOrRoomID.startsWith("81"))) {
            call(phoneOrRoomID);
        } else
            showToast("账号/会议号格式错误！");
    }

    private void call(String roomId) {
        if (phoneOrRoomID.length() == 12 && phoneOrRoomID.startsWith("81")) {
            startMeeting(phoneOrRoomID);
        } else if (phoneOrRoomID.length() == 11 && phoneOrRoomID.startsWith("1")) {
            dialingDelegate.getOtherName(AppUtil.mUser.getToken(),phoneOrRoomID,GET_OTHER_NAME);
            //startAudioVideoCall(AVChatType.AUDIO, roomId);
        }
    }

    public void startAudioVideoCall(AVChatType avChatType, String account,String name) {
        AVChatActivity.launch(EnterMeetingActivity.this, account, avChatType.getValue(), AVChatActivity.FROM_INTERNAL,name);
    }

    private void startMeeting(String roomId) {
        showDialog("正在检测会议是否开始");
        meetingDelegate.isMeetingBegin(AppUtil.mUser.getToken(), roomId, IS_MEETING_BEGIN);
    }

    @Override
    public void success(String result, byte flag) {
        super.success(result, flag);
        disDialog();
        if (flag == IS_MEETING_BEGIN)
            isMeetingBeginSuccess(result);
        else if(flag==LIVE_PUBLISH)
            livePublishSuccess(result);
        else if (flag == MEETING_IN_AUTH)
            meetingInAuthSuccess(result);
        else if (flag == MEETING_IN_CHECK)
            getLiveAddress();
        else if (flag == LIVE_PLAY)
            startLive(result);
        else if(flag==GET_OTHER_NAME)
            getOtherNameSuccess(result);
    }

    private void getOtherNameSuccess(String result){
        try {
            JSONObject obj=new JSONObject(result);
            Log.e("remote_name",obj.optString("remote_name"));
            startAudioVideoCall(AVChatType.AUDIO, phoneOrRoomID,obj.optString("remote_name"));
        } catch (JSONException e) {
        }
    }

    private void livePublishSuccess(String result){
        disDialog();
        data=result;
        meeting();
    }

    private void startLive(String result) {
        Log.e("live_play",result);
        Intent intent = new Intent(EnterMeetingActivity.this, TextureVideoActivity.class);
        intent.putExtra("roomid", phoneOrRoomID);
        intent.putExtra("meetingid", meetingid);
        intent.putExtra("isRecord", true);//是否上报拨号记录
        JSONArray array = null;
        JSONObject obj=null;
        try {
            array = new JSONArray(result);
            obj=array.getJSONObject(1);
        } catch (JSONException e) {
        }

        if (obj == null)
            return;
        String addr = obj.optString("addr");
        if (TextUtils.isEmpty(addr))
            return;
        intent.putExtra("path",addr);// "rtmp://" + addr + ":1935/txb/" + phoneOrRoomID);
        startActivity(intent);
//        try {
//            JSONObject obj=new JSONObject(result);
//            Log.e("pushUrl==","--"+obj.optString("play_back_url"));
//
//            intent.putExtra("path", obj.optString("play_back_url"));
//            startActivity(intent);
//        } catch (JSONException e) {
//        }
    }

    private void meetingInAuthSuccess(String result) {
        try {
            JSONObject obj = new JSONObject(result);
            int auth = obj.optInt("auth");
            if (auth == 0)
                checkMeetingPassword();
            else if (auth == 1)
                getLiveAddress();//有权限，直接获取
        } catch (JSONException e) {
        }
    }

    private void checkMeetingPassword() {
        final EditText et = new EditText(this);
        et.setHint("请输入入会密码");
        new AlertDialog.Builder(this).setTitle("搜索")
                .setIcon(android.R.drawable.ic_dialog_info)
                .setView(et)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        String input = et.getText().toString();
                        showToast("正在验证入会密码");
                        meetingDelegate.meetingInCheck(AppUtil.mUser.getToken(), input, MEETING_IN_CHECK);
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }

    private void getLiveAddress() {
        showDialog("正在进入房间");
       // liveDelegate.liveAddress(LIVE_ADDRESS);
        liveDelegate.livePlay(phoneOrRoomID,LIVE_PLAY);
        //  liveDelegate.livePublish(phoneOrRoomID,LIVE_ADDRESS);
    }

    private void isMeetingBeginSuccess(String result) {
        try {
            JSONObject obj = new JSONObject(result);
            name = obj.optString("name");
            roomid = obj.optString("roomid");
            meetingid = obj.optString("meetingid");
            status = obj.optInt("status");
            if (status == 1&&roomid.equals(AppUtil.mUser.getRommid())){
                showDialog();
                liveDelegate.livePublish(roomid,LIVE_PUBLISH);
            } else //if (status == 2)
                joinMeeting(roomid);
        } catch (JSONException e) {
        }
    }

    private void joinMeeting(String roomid) {
        showDialog("正在验证入会权限");
        meetingDelegate.meetingInAuth(AppUtil.mUser.getToken(), roomid, MEETING_IN_AUTH);
    }

    @Override
    public void failure(String result, byte flag, ResponseStatus status) {
        super.failure(result, flag, status);
        disDialog();
        showToast(result);
    }

    private void meeting() {
        if (!NetworkUtil.isNetAvailable(this)) {
            showToast(R.string.network_is_not_available);
            return;
        }
        if (checkPermission()) {
            createOrEnterRoom();
        } else {
            requestPermissions();
        }
    }

    /**
     * 创建会议频道
     */
    private void createChannel(final String roomId) {
        AVChatManager.getInstance().createRoom(meetingid, "avchat test", new AVChatCallback<AVChatChannelInfo>() {
            @Override
            public void onSuccess(AVChatChannelInfo avChatChannelInfo) {
                DialogMaker.dismissProgressDialog();
                ChatRoomActivity.start(EnterMeetingActivity.this, roomId,meetingid, true, false, data);
                // finish();
            }

            @Override
            public void onFailed(int i) {
                DialogMaker.dismissProgressDialog();
                if (i == 417) {
                    ChatRoomActivity.start(EnterMeetingActivity.this, roomid,meetingid,  true, false, data);
                    return;
                }
                //关闭视频预览
                //AVChatManager.getInstance().stopVideoPreview();
//离开房间
                AVChatManager.getInstance().leaveRoom2(roomid, new AVChatCallback<Void>() {

                    @Override
                    public void onSuccess(Void aVoid) {

                    }

                    @Override
                    public void onFailed(int i) {

                    }

                    @Override
                    public void onException(Throwable throwable) {

                    }
                });
//关闭音视频引擎
                // AVChatManager.getInstance().disableRtc();
                if (i == 403)
                    showToast("创建频道失败, 非法操作或没有权限");
                else
                    showToast("创建频道失败, code:" + i);
            }

            @Override
            public void onException(Throwable throwable) {
                DialogMaker.dismissProgressDialog();
            }
        });
    }

    // 进入房间
    private void enterRoom() {
        //ChatRoomActivity.start(this, roomid, false,true);
        //finish();
    }

    private void requestPermissions() {
        final List<String> missed = AVChatManager.checkPermission(this);
        List<String> showRationale = new ArrayList<>();
        for (String permission : missed) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
                showRationale.add(permission);
            }
        }
        if (showRationale.size() > 0) {
            new AlertDialog.Builder(this)
                    .setMessage("You need to allow some permission")
                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ActivityCompat.requestPermissions(EnterMeetingActivity.this, missed.toArray(new String[missed.size()]),
                                    PERMISSION_REQUEST_CODE);
                        }
                    })
                    .setNegativeButton("Cancel", null)
                    .create()
                    .show();
        } else {
            ActivityCompat.requestPermissions(this, missed.toArray(new String[missed.size()]), PERMISSION_REQUEST_CODE);
        }
    }

    //检查所有的权限
    private boolean checkPermission() {
        final List<String> missed = AVChatManager.checkPermission(this);
        if (missed.size() == 0) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case PERMISSION_REQUEST_CODE:
                if (AVChatManager.checkPermission(this).size() == 0) {
                    createOrEnterRoom();
                } else {
                    showToast("无权限");
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }

    }

    private void createOrEnterRoom() {
        DialogMaker.showProgressDialog(this, "", false);
        createChannel(roomid);
    }
}
